/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.commons.speeder.monitor.handler.impl;

import cn.ac.iie.di.commons.speeder.monitor.handler.StatHandler;
import java.util.Map;
import org.slf4j.Logger;

/**
 *
 * @author zwlin
 */
public class LogStatHandler<T> implements StatHandler<T> {

    private static final String DEFAULT_PREFIX = "Monitering Log - ";

    public static enum Type {
        TOGETHER, SEPERATELY;
    }

    public static enum Level {
        INFO, DEBUG, WARN, ERROR;
    }

    private final Logger logger;
    private final Type type;
    private final Level level;
    private String prefix;
    private String logPrefox;

    public LogStatHandler(Logger logger) {
        this(logger, Type.SEPERATELY, Level.INFO, DEFAULT_PREFIX);
    }

    public LogStatHandler(Logger logger, String prefix) {
        this(logger, Type.SEPERATELY, Level.INFO, prefix);
    }

    public LogStatHandler(Logger logger, Type type) {
        this(logger, type, Level.INFO, DEFAULT_PREFIX);
    }

    public LogStatHandler(Logger logger, Type type, Level level, String prefix) {
        this.logger = logger;
        this.type = type;
        this.level = level;
        this.prefix = prefix;
        buildLogPrefix();
    }

    public String getPrefix() {
        return prefix;
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
        buildLogPrefix();
    }

    @Override
    public void accept(Map<String, T> statMap) {
        switch (type) {
            case TOGETHER:
                log(statMap.toString());
                return;
            case SEPERATELY:
                statMap.forEach((k, v) -> log(k, v));
                return;
        }
    }

    private void log(Object... obj) {
        switch (level) {
            case DEBUG:
                logger.debug(logPrefox, obj);
                break;
            case INFO:
                logger.info(logPrefox, obj);
                break;
            case WARN:
                logger.warn(logPrefox, obj);
                break;
            case ERROR:
                logger.error(logPrefox, obj);
                break;
        }
    }

    private void buildLogPrefix() {
        switch (type) {
            case SEPERATELY:
                logPrefox = prefix + "{}:{}";
            case TOGETHER:
                logPrefox = prefix + "{}";
        }

    }

}
